
package com.sq.partner.manager.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.dao.CoinPlanConfigDao;
import com.sq.partner.manager.dao.INlifePlanDao;
import com.sq.partner.manager.mybatis.model.CoinFeeConfig;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.SaleConfig;
import com.sq.partner.manager.service.CoinFeeConfigService;
import com.sq.partner.manager.service.CoinPlanConfigService;
import com.sq.partner.manager.service.IGatewayLifePolicyListService;
import com.sq.partner.manager.service.INlifePlanConfigService;
import com.sq.partner.manager.service.SaleConfigService;
import com.sq.partner.manager.util.JsonUtils;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;

/**
 * @date 2015-11-02 新意健险跟单费用配置
 */
@Controller
@RequestMapping("/nlifeSaleConfig")
public class NlifeSaleConfigController {
	private static Logger logger = LogUtil.getLog(NlifeSaleConfigController.class);
	@Resource
	private INlifePlanDao nlifePlanDao;
	@Resource
	private INlifePlanConfigService nlifePlanConfigService;
	@Resource
	private SaleConfigService saleConfigService;
	@Resource
	private CoinFeeConfigService coinFeeConfigService;
	@Resource
	private CoinPlanConfigService coinPlanConfigService;
	@Resource
	private IGatewayLifePolicyListService lifePolicyListService;
	/**
	 * 跳转方案列表页面
	 */
	@RequestMapping(value = "/index")
	public String list() throws Exception {
		logger.info("执行跳转到跟单费用配置列表界面");
		return "nlifeProduct/nlifeSale/index";
	}
	/**新增跟单费用配置打开div*/
	@RequestMapping(value = "/addFeeConfigDiv")
	@ResponseBody
	public Map<String, Object> addFeeConfigDiv() throws Exception{
		Map<String, Object> map=new HashMap<String, Object>();
		try {
			/**查询配置维度列表*/
			List<DictDto> weidTypes=DictCache.getDict(Constants.DICT_WEID_TYPE);
			/***查询最大跟单配置代码**/
			String agentNo=saleConfigService.queryNextAgentNo("NlifeFYGD");
			map.put("weidTypes", weidTypes);
			map.put("agentNo", agentNo);	
		} catch (Exception e) {
			logger.error("查询数据库错误"+e);
		}
		return map;
	}
	/**添加或复制新增保存三费信息*/
	@RequestMapping(value = "/saveCoinFee")
	@ResponseBody
	public Map<String, Object> saveCoinFee(HttpSession session,String coinFee,String agentNo,String copyOrUpdate,String copyaddName) throws Exception{
		Map<String, Object> map=new HashMap<String, Object>();
		if(StrUtil.isEmpty(agentNo)){
			map.put("success", false);
			map.put("message", "参数异常");
			return map;
		}
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);

		String title="";
		try {
			/**判断操作类型**/
			if("copy".equals(copyOrUpdate)){
			   SaleConfig saleConfig=saleConfigService.searchSaleConfigById(agentNo);
			   saleConfig.setAgentName(copyaddName);
			   saleConfig.setInsertDate(new Date());
			   saleConfig.setOperatorCode(user.getUserCode());
				/***查询最大跟单配置代码**/
			   agentNo=saleConfigService.queryNextAgentNo("NlifeFYGD");
			   saleConfig.setAgentNo(agentNo);
			   saleConfigService.addSaleConfig(saleConfig);
			   title=",跟单费用代码"+agentNo;
			}else{
				/**更新配置名称**/
				SaleConfig sale=new SaleConfig();
				sale.setAgentNo(agentNo);
				sale.setAgentName(copyaddName);
				saleConfigService.updateSaleConfig(sale);
			}
			if(coinFeeConfigService.addCoinFee(agentNo,strToJson(coinFee, agentNo))){
				map.put("success", true);
				map.put("message", "添加成功"+title);
			}else{
				map.put("success", false);
				map.put("message", "操作失败，请重试");
			};
		} catch (Exception e) {
			logger.error("查询数据库错误"+e);
			map.put("success", false);
			map.put("message", "操作失败，请重试");
		}
		return map;
	}
	/**将String类型转换成json*/
	private List<CoinFeeConfig> strToJson(String coinFee,String agentNo){
		List<CoinFeeConfig> coins=new ArrayList<CoinFeeConfig>();
		List<Map<String,String>> list = JsonUtils.parseJson(coinFee, ArrayList.class);
		if(list!=null){
			for (Map<String, String> map : list) {
				CoinFeeConfig coin=new CoinFeeConfig();
				coin.setAgentNo(agentNo);
				coin.setBranch(map.get("branch"));
				coin.setProductType(map.get("prototype"));
				coin.setIsAgent(map.get("isAgent"));
				coin.setBusinessRate(Double.parseDouble(map.get("businessRate"))/100);
				coin.setCommRate(Double.parseDouble(map.get("commRate"))/100);
				coin.setMarketRate(Double.parseDouble(map.get("marketRate"))/100);
				coin.setSeq(Integer.parseInt(map.get("seq")));
				coin.setOprateTime(new Date());
				coin.setEmpNo(map.get("empNo"));
				coin.setSysSource(map.get("sysSource"));
				coin.setPriority(map.get("sumProp"));
				coins.add(coin);
			}
		}
		return coins;
	}
	/**新增跟单费用配置保存*/
	@RequestMapping(value = "/saveFeeConfig")
	@ResponseBody
	public Map<String, Object> saveFeeConfig(SaleConfig saleConfig,HttpServletRequest request) throws Exception{
		Map<String, Object> map=new HashMap<String, Object>();
		HttpSession session = request.getSession(); 
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		saleConfig.setInsertDate(new Date());
		/**新意见险0*/
		saleConfig.setAgentType("0");
		saleConfig.setOperatorCode(user.getUserCode());
		logger.info("操作用户"+user.getUserCode());
		try {
			boolean flag=saleConfigService.addSaleConfig(saleConfig);
			if(!flag){
				map.put("message", "保存失败");
			}else{
				map.put("message", "保存成功");	
			}
			map.put("success", flag);
		} catch (Exception e) {
			logger.error("保存跟单费用配置错误",e);
			map.put("success", false);
			map.put("message", "保存跟单费用配置错误");
		}
		return map;
	}
	/**删除跟单费用配置*/
	@RequestMapping(value = "/deleteSaleConfig")
	@ResponseBody
	public Map<String, Object> deleteSaleConfig(SaleConfig saleConfig,HttpServletRequest request) throws Exception{
		Map<String, Object> map=new HashMap<String, Object>();
		logger.info("执行删除跟单费用"+saleConfig.getAgentNo());
	
		try {
			//判断是否已关联方案
			Integer count=coinPlanConfigService.queryCoinFeeCount(saleConfig.getAgentNo());
			if(count>0){
				String planNos=coinPlanConfigService.queryCoinFeeList(saleConfig.getAgentNo());
				map.put("message", "该条费用配置信息已与出单方案"+planNos+"进行关联，不允许删除");
				map.put("success", false);
				return map;
			}
			boolean flag=saleConfigService.delSaleConfig(saleConfig);
			/**删除三费信息*/
			coinFeeConfigService.deleteCoinFee(saleConfig.getAgentNo());
			if(!flag){
				map.put("message", "删除失败");
			}else{
				map.put("message", "删除成功");	
			}
			map.put("success", flag);
		} catch (Exception e) {
			logger.error("保存跟单费用配置错误",e);
			map.put("success", false);
			map.put("message", "删除跟单费用配置错误");
		}
		return map;
	}
	/**查询列表*/
	@RequestMapping(value = "/querySalePageByCriteria")
	@ResponseBody
	public Page<Map<String,Object>> querySalePageByCriteria(HttpSession session,Page<Map<String,Object>> page,SaleConfig saleConfig) throws Exception{
		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		paramMap.put("agentType", "0");
		paramMap.put("agentNo", ("").equals(saleConfig.getAgentNo())?null:saleConfig.getAgentNo());
		paramMap.put("agentName", ("").equals(saleConfig.getAgentName())?null:saleConfig.getAgentName());
		paramMap.put("bigdate", ("").equals(saleConfig.getBigdate())?null:saleConfig.getBigdate());
		paramMap.put("smallDate", ("").equals(saleConfig.getSmallDate())?null:saleConfig.getSmallDate());
		page.setMap(paramMap);
		/**查询配置维度列表*/
		List<DictDto> weidTypes=DictCache.getDict(Constants.DICT_WEID_TYPE);
		page.getMap().put("weids", weidTypes);
		page = saleConfigService.queryPageByCriteria(page);
		return page;
	}
	/***
	 * 查询三费列表
	 */
	@RequestMapping(value = "/queryCoins")
	@ResponseBody
	public Map<String, Object> queryCoins(SaleConfig saleConfig,HttpServletRequest request) throws Exception{
		Map<String, Object> map=new HashMap<String, Object>();
		try {
			String seq=coinFeeConfigService.queryMaxSeq(saleConfig.getAgentNo());
			map.put("agentNo", Integer.parseInt(seq));
			List<CoinFeeConfig> coins=coinFeeConfigService.queryCoins(saleConfig.getAgentNo());
			map.put("coins", coins);
		} catch (Exception e) {
			logger.error("数据库操作错误",e);
			map.put("success", false);
			map.put("message", "数据库操作错误");
		}
		return map;
	}
	/***
	 * 跟单费用 维度下拉框
	 */
	@RequestMapping(value = "/querySelectOption")
	@ResponseBody
	public Map<String, Object> querySelectOption(HttpSession session) throws Exception{
		Map<String, Object> map=new HashMap<String, Object>();
		try {
			GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
			logger.info("当前登录用户的userCode为"+user.getUserCode()+",DepartmentStr:"+user.getDepartmentStr());
			if(null != user && StrUtil.isNotEmpty(user.getDepartmentStr())){
				List<CoreDept> depts=lifePolicyListService.queryPrivilegeBranch(user.getDepartmentStr());
				map.put("depts", depts);
			}
			List<DictDto> isAgents=DictCache.getDict(Constants.DICT_NLIFESALE_CHANNEL);
			List<DictDto> prodTypes=DictCache.getDict(Constants.DICT_PRODUCT_TYPE);
			map.put("isAgents", isAgents);
			map.put("prodTypes", prodTypes);
		} catch (Exception e) {
			logger.error("数据库操作错误",e);
			map.put("success", false);
			map.put("message", "数据库操作错误");
		}
		return map;
	}
	/***
	 * 查询分公司信息
	 */
	@RequestMapping(value = "/queryDeptPageByCriteria")
	@ResponseBody
	public Page<CoreDept> queryDeptPageByCriteria(Page<CoreDept> page,String deptName ,String deptCode,HttpSession session) throws Exception{
		GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		Map<String, Object>map=new HashMap<String, Object>();
		/**条件判断*/
		if(StrUtil.isNotEmpty(deptCode)){
			map.put("deptCode", "%"+deptCode+"%");
		}
		if(StrUtil.isNotEmpty(deptName)){
			map.put("deptName","%"+ deptName+"%");
		}
		page.setMap(map);
		if(null != user && StrUtil.isNotEmpty(user.getDepartmentStr())){
			logger.info("登录用户"+user.getUserCode()+"用户机构"+user.getDepartmentStr());
			 page=nlifePlanConfigService.queryDeptPageByCriteria1(page, user.getDepartmentStr());
			
		}
		return page;
	}
}
